package ug.co.icom.kyazze.healthticket;

import java.util.Date;
import java.util.List;
import java.util.Map;

import ug.co.icom.kyazze.healthticket.DataBase.Database;
import ug.co.icom.kyazze.healthticket.data.MyConnections;
import ug.co.icom.kyazze.healthticket.data.User;
import ug.co.icom.kyazze.healthticket.services.IntentServiceGetConnections;
import ug.co.icom.kyazze.healthticket.services.IntentServiceOnCreateMain;
import ug.co.icom.kyazze.healthticket.services.IntentUpdaterService;
import ug.co.icom.kyazze.healthticket.services.UpdaterService;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import de.keyboardsurfer.android.widget.crouton.ConnectionDetector;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;

public class MainActivity_NoTabs extends Activity {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;
	private String[] drawerItems;
	private int cFrag = R.string.main;
	private User user;
	static boolean initialized;
	ConnectionDetector cd;
	static Database query_handler;
	static SQLiteDatabase db;
	static Button notifCount;
	static int mNotifCount = 5;
	String sender;
	String phoneNumber;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tab_pager);
		
		Intent act = getIntent();
		sender = act.getStringExtra(MainActivity.EXTRA_MESSAGE);


		loadUserCredentials();
		createOrOpenDB();

		cd = new ConnectionDetector(getApplicationContext());

		// Check if Internet present
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			Crouton.makeText(this, "No Active Internet Connection", Style.ALERT)
					.show();

			// return;
		}
		Intent n_intent = new Intent(this, IntentServiceGetConnections.class);
		startService(n_intent);
		
		db = openOrCreateDatabase("mrDB", MODE_PRIVATE, null);
		query_handler = new Database(db);
		
		
		Intent intent = new Intent(this, IntentServiceOnCreateMain.class);
		startService(intent);
		

		
		//if(message.equals("loadconnections")){
			
		//}
		

		// Initialize and load PHR element fragment
//		Fragment fragment = new MainItemsFragment();
//		FragmentManager fragmentManager = getFragmentManager();
//		fragmentManager.beginTransaction()
//				.replace(R.id.content_frame, fragment).commit();

		drawerItems = getResources().getStringArray(R.array.draweritems_array_notabs);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);


		// set a custom shadow that overlays the main content when the drawer
		// opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);
		// set up the drawer's list view with items and click listener
		mDrawerList.setAdapter(new ArrayAdapter<String>(this,
				R.layout.drawer_list_item, drawerItems));
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		// enable ActionBar app icon to behave as action to toggle nav drawer
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setDisplayShowHomeEnabled(true);
		getActionBar().setDisplayShowTitleEnabled(false);

		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				// getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				// getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			selectItem(0);
		}
	}

	private void loadUserCredentials() {
		//user = (User) getIntent().getSerializableExtra("user");
		SharedPreferences settings = getSharedPreferences("ULS", MODE_PRIVATE);
		
		phoneNumber  = settings.getString("uName","");	
//		String pWord  = settings.getString("pWord","");
//		String fName  = settings.getString("fName","");
//		String lName  = settings.getString("lName","");
//		String oName  = settings.getString("oName","");
//		String add  = settings.getString("add","");
//		String bt  = settings.getString("bt","");
//		Boolean fem  = settings.getBoolean("fem", false);
//		String dob  = settings.getString("dob","");
//		String ema  = settings.getString("ema","");
//		
//		user.PhoneNumber = uName;
//		user.PassCode = pWord;
//		user.FirstName = fName;
//		user.LastName = lName;
//		user.OtherNames = oName;
//		user.Address = add;
//		user.BloodType =bt;
//		user.Female = fem;
		//user.DateOfBirth = getDateFromString(dob);
//		user.Email = ema;
		
		

		//public Boolean Female;
		//public Date DateOfBirth;

	}

	private void createOrOpenDB() {
		SQLiteDatabase db = openOrCreateDatabase("mrDB", MODE_PRIVATE, null);
		Database database = new Database(db);
		database.createOrOpenDB();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainactionbar_menu, menu);

		// Associate searchable configuration with the SearchView
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));
		
		View count = menu.findItem(R.id.action_notifications).getActionView();
	    notifCount = (Button) count.findViewById(R.id.notif_count);
	    notifCount.setText(String.valueOf(mNotifCount));
		
		return super.onCreateOptionsMenu(menu);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content
		// view
		// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		// menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		
		//explicit intent
		@SuppressWarnings("unused")
		Intent intent = new Intent(this,UpdaterService.class);
		Intent intent_service = new Intent(this,IntentUpdaterService.class);
		
		
		// Handle action buttons
		switch (item.getItemId()) {
		case R.id.action_search:
			return true;
		case R.id.action_connections:
			loadConnections();
			return true;
		case R.id.action_notifications:
			loadNotifications(null);
			return true;
//		case R.id.item_start_sync:
//			startService(intent);
//			Crouton.makeText(this, "Syncing service started", Style.CONFIRM)
//			.show();
//			return true;
//		case R.id.item_stop_sync_service:
//			stopService(intent);
//			Crouton.makeText(this, "Syncing service stoped", Style.INFO)
//			.show();
//			return true;
		case R.id.item_intent_service:
			startService(intent_service);
			return true;
		
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void loadNotifications(View v) {
		if (cFrag != R.string.notifications) {
			
			Bundle bundle = new Bundle();
    		bundle.putSerializable("phoneNumber", phoneNumber);
    		//bundle.putSerializable("phoneNumber", 27222);
			
			cFrag = R.string.notifications;
			Fragment fragment = new NotificationsFragment();
			fragment.setArguments(bundle);
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.content_frame, fragment).commit();
		} else {
			cFrag = R.string.main;
			Fragment fragment = new MainItemsFragment();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.content_frame, fragment).commit();
		}
	}

	public void loadConnections() {
		
		cFrag = R.string.profile;
		Fragment fragment = new ProfileFragment();
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.content_frame, fragment).commit();
		
//		if (cFrag != R.string.connections) {
			
//			Bundle bundle = new Bundle();
//    		bundle.putSerializable("phoneNumber", phoneNumber);
//			
//			cFrag = R.string.connections; 			//Fragment fragment = new ConnectionsFragment();
//			Fragment fragment = new NotificationsFragment();
//			fragment.setArguments(bundle);
//			FragmentManager fragmentManager = getFragmentManager();
//			fragmentManager.beginTransaction()
//					.replace(R.id.content_frame, fragment).commit();
//		} else {
//			cFrag = R.string.profile;
//			Fragment fragment = new ProfileFragment();
//			FragmentManager fragmentManager = getFragmentManager();
//			fragmentManager.beginTransaction()
//					.replace(R.id.content_frame, fragment).commit();
//		}
	}

	/* The click listner for ListView in the navigation drawer */
	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			selectItem(position);
		}
	}

	private void selectItem(int position) {
		Intent intent;
		if (position == 0) {
			
    		Bundle bundle = new Bundle();
    		bundle.putSerializable("user", user);
    		
    		cFrag = R.string.profile;
	    	Fragment fragment = new ProfileFragment();
	    	fragment.setArguments(bundle);
	    	FragmentManager fragmentManager = getFragmentManager();
	        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
		
		} else if (position == 1) {

			cFrag = R.string.emergencycontacts;
			Fragment fragment = new EmergencyContactsFragment();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.content_frame, fragment).commit();
			

		} else if (position == 2) {

			cFrag = R.string.permissions;
			Fragment fragment = new PermissionsFragment();
			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction()
					.replace(R.id.content_frame, fragment).commit();
			
		} else if (position == 3) {
			
			cFrag = R.string.main;
			 intent = new Intent(getBaseContext(), MainActivity.class);
            //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);

		} else if (position == 4) {
			SharedPreferences settings = getSharedPreferences("ULS", 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putBoolean("rem", false);
			editor.putString("uName", "");
			editor.putString("pWord", "");
			editor.putString("fName", "");
			editor.putString("lName", "");
			editor.putString("oName", "");
			editor.putString("add", "");
			editor.putString("bt", "");
			editor.putBoolean("fem", false);
			editor.putString("dob", "");
			editor.putString("ema", "");
			editor.commit();
			finish();

	
		}

		// update selected item and title, then close the drawer
		mDrawerList.setItemChecked(position, true);
		// setTitle(drawerItems[position]);
		mDrawerLayout.closeDrawer(mDrawerList);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	/**
	 * Given the sdcard file path, the method sets the global variable ImageName
	 * 
	 * @param sdcardPath_val
	 */
	@SuppressWarnings("unused")
	private String getFileName(String sdcardPath_val) {
		String File_Name = "";
		if (null != sdcardPath_val && sdcardPath_val.length() > 0) {
			int beginIndex = sdcardPath_val.lastIndexOf("/");
			if (beginIndex != -1) {
				File_Name = sdcardPath_val.substring(beginIndex,
						sdcardPath_val.length()); // not forgot to put check if(
													// endIndex != -1)

			}
		}
		return File_Name;

	}
	
	/**
	 * Get all valid connections
	 * @return
	 */
	public static String[] connects(){
		
		List<MyConnections> all_objects = query_handler.getAllConnections();
		String[] outputx = new String[all_objects.size()];	
		int i = 0;
		for (MyConnections con_obj : all_objects) {
			String connection_name = con_obj.getFirstname() + " "+ con_obj.getLastname();
			outputx[i] = connection_name;
			i++;
			//outputx.add(allergy_name1);
		}
		//db.close();
		return outputx;	
	}

	@Override
	protected void onStart() {
		super.onStart();
		
		if(sender.equals("loadconnections")){
			//loadNotifications(null);//
			loadConnections();
		}
		else if (sender.equals("profile")){
			selectItem(0);		
		}
		else if (sender.equals("emergencycontacts")){
			selectItem(1);		
		}
		else if (sender.equals("permissions")){
			selectItem(2);		
		}
		else if (sender.equals("loadnotifications")){
			loadNotifications(null);		
		}
		

	}
	



	

}
